<template>
    <div>
        <div class="y-ipt" v-if="type=='text'">
            <input class="ipt" v-model="ipt" type="text" v-maxlent:ipt="maxlent">
            <span class="sp">{{ipt.length}}/{{maxlent}}</span>
        </div>
        <div class="y-ipt" v-if="type=='textarea'">
            <textarea class="text" v-model="text" v-maxlent:text="maxlent"></textarea>
            <span class="sp">{{text.length}}/{{maxlent}}</span>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        type: {
            type: String,
            default: "text"
        },
        maxlent: {
            type: Number,
            default: 10
        }
    },
    data() {
        return {
            ipt: "",
            text: ""
        };
    },
    methods: {},
    directives: {
        maxlent: {
            // 指令的定义
            update: function(el, { value, arg }, vnode) {
                el.addEventListener("input", event => {
                    if (el.value.length > value - 1) {
                        el.value = el.value.substring(0, value);
                        vnode.context[arg] = el.value;
                        el.style.color = "red";
                    } else {
                        el.style.color = "black";
                    }
                });
            }
        }
    }
};
</script>

<style scoped>
.y-ipt {
    position: relative;
    display: inline-block;
}
.ipt {
    width: 100%;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: none;
    padding: 0 15px;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.sp {
    position: absolute;
    height: 100%;
    right: 5px;
    top: 0;
    text-align: center;
    color: #c0c4cc;
    transition: all 0.3s;
    font-size: 14px;
    display: inline-flex;
    align-items: center;
    padding: 0 5px;
}

.text {
    display: block;
    resize: vertical;
    padding: 5px 15px;
    line-height: 1.5;
    box-sizing: border-box;
    width: 100%;
    font-size: inherit;
    color: #606266;
    background-color: #fff;
    background-image: none;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.textsp {
    color: #909399;
    background: #fff;
    position: absolute;
    font-size: 12px;
    bottom: 5px;
    right: 10px;
}
</style>